﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Training.Dia1.Data.Entities;

namespace Training.Dia1.Data.Managers
{
    public class MeasureUnitManager
    {
        public static IList<MeasureUnit> GetList(string filter)
        {
            using (TrainingDia1DbContext ctx = new TrainingDia1DbContext())
            {
                return ctx.MeasureUnits.Where(u => u.Name.Contains(filter)).ToList();
            }
        }

        public static MeasureUnit Create(MeasureUnit measureUnit)
        {
            using (TrainingDia1DbContext ctx = new TrainingDia1DbContext())
            {
                MeasureUnit measureUnitDB = ctx.MeasureUnits.Add(measureUnit);
                
                ctx.SaveChanges();
                return measureUnitDB;
            }
        }
        public static MeasureUnit Update(MeasureUnit measureUnit)
        {
            using (TrainingDia1DbContext ctx = new TrainingDia1DbContext())
            {
                ctx.Entry(measureUnit).State = EntityState.Modified;
                ctx.SaveChanges();
                return measureUnit;
            }
        }
        public static MeasureUnit GetById(Guid id) 
        {
            using (TrainingDia1DbContext ctx = new TrainingDia1DbContext())
            {
                MeasureUnit measureUnitDB = ctx.MeasureUnits.Find(id);
                if (measureUnitDB == null)
                {
                    throw new Exception("MeasureUnit not found in data base");
                }
                return ctx.MeasureUnits.Find(id);
            }
        }
        public static void Delete(Guid id)
        {
            using (TrainingDia1DbContext ctx = new TrainingDia1DbContext())
            {
                MeasureUnit measureUnitDB = ctx.MeasureUnits.Find(id);
                if (measureUnitDB == null)
                {
                    throw new Exception("MeasureUnit not found in data base");
                }
                ctx.MeasureUnits.Remove(measureUnitDB);
                ctx.SaveChanges();
            }
        }

    }
}
